package com.explorati.LeetCode206.reverseLinkedList;

import com.explorati.LeetCode206.reverseLinkedList.Solution.ListNode;

/**
 * 206. Reverse Linked List 第一种解法：使用三个指针
 * 
 * Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
 * 
 * @author explorati
 *
 */
public class Solution1 {
	public class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
		}
	}

	public static ListNode reverseList(ListNode head) {
		if (head == null) {
			return null;
		}
		if (head.next == null) {
			return head;
		}

		ListNode pre = null;
		ListNode cur = head;

		while (cur != null) {
			ListNode next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
			head = pre;
		}
		return head;
	}

	public static void main(String[] args) {
		Solution1 s = new Solution1();
		ListNode head = s.new ListNode(1);
		ListNode cur = head;
		for (int i = 2; i <= 5; i++) {
			cur.next = s.new ListNode(i);
			cur = cur.next;
		}

		ListNode test = head;
		while (test != null) {
			System.out.print(test.val);
			if (test.next != null) {
				System.out.print("->");
			}
			test = test.next;
		}

		System.out.println();

		ListNode reverseListHead = reverseList(head);
		while (reverseListHead != null) {
			System.out.print(reverseListHead.val);
			if (reverseListHead.next != null) {
				System.out.print("->");
			}
			reverseListHead = reverseListHead.next;
		}
	}
}
